﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlTypes;
using Spring.Data.Common;
using Spring.Data.Generic;
using Spring.Data.Objects.Generic;

namespace MySearch
{
    internal class UniqueIDGenerator : StoredProcedure
    {
        private static string procedureName = "sp_get_unique_id";
        private static UniqueIDGenerator sp;
        private static string _ID_FORMAT = "000000000";

        static UniqueIDGenerator()
        {
            sp = new UniqueIDGenerator(AppConfigurer.AdoTemplate.DbProvider);
        }

        private UniqueIDGenerator(IDbProvider dbProvider)
            : base(dbProvider, procedureName)
        {
            DeriveParameters();
            Compile();
        }

        public static string Get(string prefix)
        {
            if (String.IsNullOrEmpty(prefix))
                prefix = "U";

            IDictionary outParams = sp.ExecuteNonQuery(new object[0]);
            int nID = Int32.Parse(outParams["@uid"].ToString());

            return prefix + nID.ToString(_ID_FORMAT);
        }

    }

    internal static class DbConvert
    {
        public static string ListToInClause(IList<string> lst)
        {
            //Check parameter
            if (lst == null)
                lst = new List<string>();

            StringBuilder sb = new StringBuilder();
            sb.Append("''");
            foreach (string strT in lst)
                sb.Append(",'" + strT + "' ");

            return sb.ToString();
        }

        public static SqlDateTime Convert(DateTime dt)
        {
            return dt == DateTime.MinValue ? SqlDateTime.Null : new SqlDateTime(dt);
        }

        public static string ListToXMLForID(IList<string> lst)
        {
            if (lst == null)
                lst = new List<string>();

            StringBuilder sb = new StringBuilder(lst.Count * 17 + 1);
            foreach (string strT in lst)
                sb.Append(String.Format("{0}{1}{2}","<I>",strT,"</I>"));

            return sb.ToString();
        }
    }

}
